import { Room } from '../types/Room';

const cleanup = (value?: string | null) => {
  if (!value) return '';
  return String(value).replace(/\r|\n/g, ' ').trim();
};

export const buildRoomsExportText = (rooms: Room[]): string => {
  if (!rooms || rooms.length === 0) {
    return '';
  }

  const lines = rooms.map(room => {
    const parts = [cleanup(room.id)];
    const title = cleanup(room.title);
    const streamer = cleanup(room.streamerName);

    if (title) {
      parts.push(title);
    }
    if (streamer) {
      parts.push(streamer);
    }

    return parts.join(',');
  });

  return lines.join('\r\n');
};

export const triggerRoomsExportDownload = (rooms: Room[], fileName = 'rooms.txt') => {
  const text = buildRoomsExportText(rooms);
  const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
  const url = URL.createObjectURL(blob);

  try {
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } finally {
    URL.revokeObjectURL(url);
  }
};
